#include <stdio.h>
#include <string.h>
#include <openssl/blowfish.h>

/* Macros for swapping constant values in the preprocessing stage. */
#define OSSwapConstInt16(x) ((((x) & 0xff00) >> 8) | (((x) & 0x00ff) << 8))

#define OSSwapConstInt32(x) ((OSSwapConstInt16(x) << 16) | \
			     (OSSwapConstInt16((x) >> 16)))

#define OSSwapConstInt64(x) ((OSSwapConstInt32(x) << 32) | \
			     (OSSwapConstInt32((x) >> 32)))

#define GetInt32BE(buf) ((buf)[3] | ((buf)[2] << 8) | ((buf)[1] << 16) | ((buf)[0] << 24))

int main()
{
	unsigned char outbuf[1024] = {0};
	int outlen = 1024;

	const unsigned char key[] = {0x6B, 0x60, 0xCB, 0x5B, 0x82, 0xCE, 0x90, 0xB1, 0xCC, 0x2B, 0x6C, 0x55, 0x6C, 0x6C, 0x6C, 0x6C};
	unsigned char intext[] = {0xb2, 0xfb, 0xda, 0x4f, 0xc9, 0x23, 0x47, 0xa0, 0x10, 0xb3, 0x37, 0x67, 0x9b, 0x2f,\
	0xb4, 0x3e, 0x69, 0xb7, 0x13, 0xef, 0x6b, 0x5c, 0xd0, 0xb9, 0x16, 0x1c, 0x71, 0x5d, 0x0a, 0x0d,\
	0x96, 0x9b, 0x09, 0x3e, 0x3f, 0xd9, 0x42, 0x82, 0xc6, 0x54, 0xd7, 0x9b, 0x5f, 0x10, 0x1d, 0xdb,\
	0x26, 0xa0, 0x6d, 0x7d, 0xcd, 0xcc, 0xf8, 0x01, 0xfc, 0xd8, 0x43, 0xf6, 0xdd, 0xc0, 0x9c, 0x41,\
	0x98, 0xc8, 0x0c, 0x94, 0x87, 0x44, 0xf7, 0xc3, 0xf7, 0xba, 0xf3, 0xc9, 0x46, 0x45, 0xd0, 0x49,\
	0xde, 0x4d, 0x33, 0xee, 0x6b, 0x3a, 0x8c, 0x18, 0xce, 0xe0, 0x82, 0x97, 0x4c, 0xd8, 0x91, 0xf7,\
	0xdf, 0xbe, 0x7c, 0xf6, 0x59, 0x2c, 0xee, 0x5a, 0x95, 0xb3, 0xcd, 0xeb, 0x86, 0xa0, 0xd9, 0x05,\
	0x16, 0x41, 0xa3, 0x90, 0x58, 0xcf, 0x0d, 0xba, 0x87, 0x90, 0x91, 0xe6, 0x08, 0xfd, 0xbc, 0x6d,\
	0xff, 0x51, 0xcf, 0xe0, 0xf9, 0xc6, 0x71, 0x3b, 0xa0, 0xcc, 0x14, 0x3d, 0x46, 0x79, 0xd4, 0x9b,\
	0x0c, 0x37, 0x01, 0x77, 0x99, 0x87, 0xcc, 0x6c, 0x25, 0x01, 0x31, 0x01, 0xea, 0xfc, 0xac, 0xe1,\
	0x57, 0x4d, 0xa5, 0xa2, 0xda, 0xa3, 0x98, 0xc4, 0x83, 0x7a, 0x72, 0x8c, 0xcb, 0x52, 0xbd, 0x16,\
	0x1c, 0x77, 0xb6, 0x7c, 0x52, 0xf7, 0x72, 0xab, 0xee, 0xba, 0x56, 0xb5, 0x76, 0xbf, 0xfa, 0xc5,\
	0x6c, 0xe6};
	int inlen = sizeof(intext);

	printf("keylen= %d\n", sizeof(key));
	printf("inlen = %d\n", inlen);

	BF_KEY bf_key;
	BF_set_key(&bf_key, sizeof(key), key);
	
	unsigned int temp[2] = {0};
	for (int i = 0; i < inlen; i += 8)
	{
		temp[0] = GetInt32BE(&intext[i]);
		temp[1] = GetInt32BE(&intext[i+4]);
		BF_ecb_encrypt((unsigned char*)&temp, &outbuf[i], &bf_key, BF_DECRYPT); 
	}

	
	outlen = inlen;

	int i = 0;
	while (i < outlen)
	{
		printf("%02X ", outbuf[i]);
		i++;
		if (i % 16 == 0) printf("\n");
	}

	printf("\n");

	int ecx = GetInt32BE(&outbuf[outlen-4]);
	*(int*)(&outbuf[outlen-4]) = ecx;
	int edx = 0;
	for (int i = outlen-8; i >= 0; i-=4)
	{
		edx = GetInt32BE(&outbuf[i]);
		edx ^= ecx;
		ecx -= edx;
		*(int*)(&outbuf[i]) = edx;
	}

	i = 0;
	while (i < outlen)
	{
		printf("%02X ", outbuf[i]);
		i++;
		if (i % 16 == 0) printf("\n");
	}

	printf("\n");

	return 0;
}
